package es.mgil.signalStrength;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.chart.TimeChart;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;

public class MainActivity extends Activity {
	private TelephonyManager tm;
	private MyPhoneStateListener listener;
	private TimeChart chart;
	private GraphicalView mView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);

		listener = new MyPhoneStateListener();
		tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		tm.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
	}

	@Override
	protected void onPause() {
		super.onPause();
		tm.listen(listener, PhoneStateListener.LISTEN_NONE);
	}

	@Override
	protected void onResume() {
		super.onResume();
		tm.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
	}

	private class MyPhoneStateListener extends PhoneStateListener {
		private List<SignalData> list = new ArrayList<SignalData>();
		private String[] titles = new String[] { "CDMA RRSI", "CDMA EC/IO",
				"GSM Signal Strength" };
		private int[] colors = new int[] { Color.RED, Color.GREEN, Color.BLUE };
		private PointStyle[] styles = new PointStyle[] { PointStyle.POINT,
				PointStyle.POINT, PointStyle.POINT };

		@Override
		public void onSignalStrengthsChanged(SignalStrength signalStrength) {
			super.onSignalStrengthsChanged(signalStrength);

			Date now = Calendar.getInstance().getTime();
			SignalData data = new SignalData(now, signalStrength.getCdmaDbm(),
					signalStrength.getCdmaEcio(),
					signalStrength.getGsmSignalStrength());
			list.add(data);

			List<Date[]> dates = new ArrayList<Date[]>();
			List<double[]> values = new ArrayList<double[]>();
			double max = Integer.MIN_VALUE;
			double min = Integer.MAX_VALUE;
			for (int i = 0; i < titles.length; i++) {
				dates.add(new Date[list.size()]);
				values.add(new double[list.size()]);

				for (int j = 0; j < list.size(); j++) {
					dates.get(i)[j] = list.get(j).date;
					switch (i) {
					case 0:
						values.get(i)[j] = list.get(j).cdma_rssi;
						break;
					case 1:
						values.get(i)[j] = list.get(j).cdma_ec_io;
						break;
					case 2:
						values.get(i)[j] = list.get(j).gsm_ss;
						break;
					}

					if (max < values.get(i)[j]) {
						max = values.get(i)[j];
					}
					if (min > values.get(i)[j]) {
						min = values.get(i)[j];
					}
				}
			}

			XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
			setChartSettings(renderer, "Signal Strength", "", "dB",
					dates.get(0)[0].getTime() - 3000,
					dates.get(0)[dates.get(0).length - 1].getTime() + 3000,
					min - 2, max + 2, Color.GRAY, Color.LTGRAY);
			renderer.setXLabels(10);
			renderer.setYLabels(10);
			renderer.setXLabelsAngle(-45);
			renderer.setZoomButtonsVisible(true);

			for (int i = 0; i < renderer.getSeriesRendererCount(); i++) {
				SimpleSeriesRenderer seriesRenderer = renderer
						.getSeriesRendererAt(i);
				seriesRenderer.setDisplayChartValues(true);
			}

			XYMultipleSeriesDataset dataset = buildDateDataset(titles, dates,
					values);

			chart = new TimeChart(dataset, renderer);
			chart.setDateFormat("HH:mm:ss");
			mView = new GraphicalView(MainActivity.this, chart);
			setContentView(mView);
		}
	}

	private class SignalData {
		private Date date;
		private double cdma_rssi;
		private double cdma_ec_io;
		private double gsm_ss;

		public SignalData(Date date, double cdma_rssi, double cdma_ec_io,
				double gsm_ss) {
			this.date = date;
			this.cdma_rssi = cdma_rssi;
			this.cdma_ec_io = cdma_ec_io;
			this.gsm_ss = gsm_ss;
		}
	}

	private XYMultipleSeriesRenderer buildRenderer(int[] colors,
			PointStyle[] styles) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();

		renderer.setAxisTitleTextSize(16);
		renderer.setChartTitleTextSize(20);
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setPointSize(5f);
//		renderer.setMargins(new int[] { 20, 30, 15, 20 });
		renderer.setMargins(new int[] { 30, 25, 30, 10 });
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			renderer.addSeriesRenderer(r);
		}

		return renderer;
	}

	private void setChartSettings(XYMultipleSeriesRenderer renderer,
			String title, String xTitle, String yTitle, double xMin,
			double xMax, double yMin, double yMax, int axesColor,
			int labelsColor) {
		renderer.setChartTitle(title);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		renderer.setAxesColor(axesColor);
		renderer.setLabelsColor(labelsColor);
	}

	private XYMultipleSeriesDataset buildDateDataset(String[] titles,
			List<Date[]> xValues, List<double[]> yValues) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			TimeSeries series = new TimeSeries(titles[i]);
			Date[] xV = xValues.get(i);
			double[] yV = yValues.get(i);
			int seriesLength = xV.length;
			for (int k = 0; k < seriesLength; k++) {
				series.add(xV[k], yV[k]);
			}
			dataset.addSeries(series);
		}
		return dataset;
	}
}
